package com.dingwei.superiordiary.mvp.presenter;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import com.dingwei.superiordiary.R;
import com.dingwei.superiordiary.base.MyBaseBean;
import com.dingwei.superiordiary.bean.CommodityDetailsBean;
import com.dingwei.superiordiary.bean.FailsBean;
import com.dingwei.superiordiary.bean.GoodsCommentSuccessBean;
import com.dingwei.superiordiary.custom.myCallback;
import com.dingwei.superiordiary.mvp.view.Contract;
import com.dingwei.superiordiary.ui.activity.LoginActivity;
import com.dingwei.superiordiary.ui.activity.WebViewActivity;
import com.lihao.baselibrary.base.BaseActivity;
import com.lihao.baselibrary.base.URLS;
import com.lihao.baselibrary.base.basePresenter;
import com.lihao.baselibrary.utils.ScreenUtils;

import org.xutils.http.RequestParams;
import org.xutils.x;

import static com.scwang.smartrefresh.layout.util.DensityUtil.dp2px;

/**
 * Created by lihao on 2017/9/12.
 */

public class CommodityDetailsPresenter extends basePresenter {

    private Contract.CommodityDetailsView commodityDetailsView;
    private Dialog bottomDialog;
    private PopupWindow popupWindow;

    public CommodityDetailsPresenter(Contract.CommodityDetailsView view) {
        super(view);
        this.commodityDetailsView = view;
    }

    public void initData(String id) {
        RequestParams rp = new RequestParams(URLS.HOST + URLS.COMMODITY_DETAILS);
        rp.addBodyParameter("id", id);
        rp.addBodyParameter("sessionid", BaseActivity.value.getToken());
        x.http().post(rp, new myCallback(BaseActivity.context, CommodityDetailsBean.class, rp) {
            @Override
            public void back(MyBaseBean baseBean, String result) {
                CommodityDetailsBean bean = (CommodityDetailsBean) baseBean;
                commodityDetailsView.getData(bean);
            }

            @Override
            public void fail(FailsBean baseBean, String result) {
                commodityDetailsView.onFail();
            }
        });
    }

    public void showEvaluationDialog(final String id, final String pid, final int position) {
        View view = LayoutInflater.from(BaseActivity.context).inflate(R.layout.dialog_evaluation, null);
        final EditText etEvaluation = (EditText) view.findViewById(R.id.et_evaluation);
        Button btnAddComment = (Button) view.findViewById(R.id.btn_add_comment);
        btnAddComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                saveComment(id, pid, etEvaluation.getText().toString(),position);
                bottomDialog.dismiss();
            }
        });
        view.measure(0, 0);
        bottomDialog = new Dialog(BaseActivity.context, R.style.Theme_Light_Dialog);
        bottomDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        bottomDialog.setContentView(view);
        Window dialogWindow = bottomDialog.getWindow();
        //设置dialog在屏幕底部
        dialogWindow.setGravity(Gravity.BOTTOM);
        //设置dialog弹出时的动画效果，从屏幕底部向上弹出
        dialogWindow.setWindowAnimations(R.style.dialogstyle);
        dialogWindow.getDecorView().setPadding(0, 0, 0, 0);
        //获得window窗口的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        //设置窗口宽度为充满全屏
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        //设置窗口高度为包裹内容
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        //将设置好的属性set回去
        dialogWindow.setAttributes(lp);
        bottomDialog.show();
    }


    private void saveComment(String id, final String pid, String content, final int position) {
        RequestParams rp = new RequestParams(URLS.HOST + URLS.PRODUCT_SAVE_COMMENT);
        rp.addBodyParameter("id", id);
        rp.addBodyParameter("pid", pid);
        rp.addBodyParameter("content", content);
        rp.addBodyParameter("sessionid", BaseActivity.value.getToken());

        x.http().post(rp, new myCallback(BaseActivity.context, GoodsCommentSuccessBean.class) {
            @Override
            public void back(MyBaseBean baseBean, String result) {
                showToast(baseBean.message);
                GoodsCommentSuccessBean bean = (GoodsCommentSuccessBean) baseBean;
                commodityDetailsView.commentSuccess(bean,position);
            }

            @Override
            public void fail(FailsBean baseBean, String result) {

            }
        });
    }

    public void collection(String id) {
        RequestParams rp = new RequestParams(URLS.HOST + URLS.SAVE_COLLECTION);
        rp.addBodyParameter("id", id);
        rp.addBodyParameter("type", "1");
        rp.addBodyParameter("sessionid", BaseActivity.value.getToken());
        x.http().post(rp, new myCallback(BaseActivity.context, MyBaseBean.class, rp) {
            @Override
            public void back(MyBaseBean baseBean, String result) {
                showToast(baseBean.message);
                commodityDetailsView.collectSuccess();
            }

            @Override
            public void fail(FailsBean baseBean, String result) {
            }
        });
    }


    public void showSortPopupWindow(View tvShow, final boolean isLike,final boolean isCollect) {
        View view = LayoutInflater.from(BaseActivity.context).inflate(R.layout.pop_share_like, null);
        LinearLayout llShare = (LinearLayout) view.findViewById(R.id.ll_share);
        LinearLayout llLike = (LinearLayout) view.findViewById(R.id.ll_like);
        LinearLayout llCollect = (LinearLayout) view.findViewById(R.id.ll_collect);
        LinearLayout ll_kefu = (LinearLayout) view.findViewById(R.id.ll_kefu);
        ImageView imgLike = (ImageView) view.findViewById(R.id.img_like);
        ImageView imgCollect = (ImageView) view.findViewById(R.id.img_collect);
        if (isLike) {
            imgLike.setImageResource(R.drawable.pic_zan2);
        } else {
            imgLike.setImageResource(R.drawable.pic_zan1);
        }
        if (isCollect) {
            imgCollect.setImageResource(R.drawable.shouchang_select_image);
        } else {
            imgCollect.setImageResource(R.drawable.shouchang_nomarl_image);
        }
        LinearLayout llBg = (LinearLayout) view.findViewById(R.id.ll_bg);
        llShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                commodityDetailsView.share();
            }
        });
        llLike.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                commodityDetailsView.likeGoods();
            }
        });
        llCollect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
                commodityDetailsView.CollectGoods();
            }
        });
        ll_kefu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
                Intent intent = new Intent(BaseActivity.context,WebViewActivity.class);
                intent.putExtra("title","客服");
                intent.putExtra("url","http://www16.53kf.com/m.php?cid=72188509&arg=10188509&style=1");
                BaseActivity.context.startActivity(intent);
            }
        });
        popupWindow = new PopupWindow(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
        popupWindow.setContentView(view);
        popupWindow.setFocusable(true);
        popupWindow.setTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setOutsideTouchable(true);
        int windowPos[] = calculatePopWindowPos(tvShow, view, llBg);
        popupWindow.showAtLocation(view, Gravity.TOP | Gravity.START, windowPos[0], windowPos[1]);
        backgroundAlpha(0.4f);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1);
            }
        });
    }


    private void backgroundAlpha(float f) {
        WindowManager.LayoutParams lp = BaseActivity.context.getWindow().getAttributes();
        lp.alpha = f;
        BaseActivity.context.getWindow().setAttributes(lp);
    }

    /**
     * 计算出来的位置，y方向就在anchorView的上面和下面对齐显示，x方向就是与屏幕右边对齐显示
     * 如果anchorView的位置有变化，就可以适当自己额外加入偏移来修正
     *
     * @param anchorView  呼出window的view
     * @param contentView window的内容布局
     * @return window显示的左上角的xOff, yOff坐标
     */
    private int[] calculatePopWindowPos(final View anchorView, final View contentView, LinearLayout llBg) {
        final int windowPos[] = new int[2];
        final int anchorLoc[] = new int[2];
        // 获取锚点View在屏幕上的左上角坐标位置
        anchorView.getLocationOnScreen(anchorLoc);
        final int anchorHeight = anchorView.getHeight();
        // 获取屏幕的高宽
        final int screenHeight = ScreenUtils.getScreenHeight(anchorView.getContext());
        final int screenWidth = ScreenUtils.getScreenWidth(anchorView.getContext());
        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        // 计算contentView的高宽
        final int windowHeight = contentView.getMeasuredHeight();
        final int windowWidth = contentView.getMeasuredWidth();
        // 判断需要向上弹出还是向下弹出显示
        final boolean isNeedShowUp = (screenHeight - anchorLoc[1] - anchorHeight < windowHeight);
        if (isNeedShowUp) {
            windowPos[0] = screenWidth - windowWidth;
            windowPos[1] = anchorLoc[1] - windowHeight;
            llBg.setPadding(0, 0, 0, dp2px(10));
            llBg.setBackgroundResource(R.drawable.pic2t);
        } else {
            llBg.setPadding(0, dp2px(10), 0, 0);
            llBg.setBackgroundResource(R.drawable.pic1j);
            windowPos[0] = screenWidth - windowWidth;
            windowPos[1] = anchorLoc[1] + anchorHeight;
        }
        return windowPos;
    }

    public void like(String id) {
        if (!BaseActivity.value.getIsLogin()){
            Intent intent = new Intent(BaseActivity.context,LoginActivity.class);
            BaseActivity.context.startActivity(intent);
            return;
        }
        RequestParams rp = new RequestParams(URLS.HOST+URLS.PRODUCT_LIKES);
        rp.addBodyParameter("sessionid", BaseActivity.value.getToken());
        rp.addBodyParameter("id",id);
        x.http().post(rp, new myCallback(BaseActivity.context, MyBaseBean.class, rp) {
            @Override
            public void back(MyBaseBean baseBean, String result) {
                showToast(baseBean.message);
                commodityDetailsView.LikeSuccess();
            }

            @Override
            public void fail(FailsBean baseBean, String result) {
            }
        });
    }


    public void commentLike(String id, final int position) {
        if (!BaseActivity.value.getIsLogin()){
            Intent intent = new Intent(BaseActivity.context,LoginActivity.class);
            BaseActivity.context.startActivity(intent);
            return;
        }
        RequestParams rp = new RequestParams(URLS.HOST+URLS.PRODUCT_LIKES_COMMENT);
        rp.addBodyParameter("id",id);
        rp.addBodyParameter("sessionid",BaseActivity.value.getToken());

        x.http().post(rp, new myCallback(BaseActivity.context, MyBaseBean.class) {
            @Override
            public void back(MyBaseBean baseBean, String result) {
                showToast("点赞成功");
                commodityDetailsView.commentLikeSuccess(position);
            }

            @Override
            public void fail(FailsBean baseBean, String result) {
            }
        });
    }
}
